package com.habdqn.studentmanager.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.github.pagehelper.PageInfo;
import com.github.xiaofan1519.verify.core.Verify;
import com.github.xiaofan1519.verify.exception.VerifyException;
import com.habdqn.studentmanager.bean.Classes;
import com.habdqn.studentmanager.bean.Dictionary;
import com.habdqn.studentmanager.bean.Employment;
import com.habdqn.studentmanager.bean.Product;
import com.habdqn.studentmanager.bean.Student;
import com.habdqn.studentmanager.bean.ajax.Response;
import com.habdqn.studentmanager.bean.condition.BigDecimalCondition;
import com.habdqn.studentmanager.bean.condition.DateCondition;
import com.habdqn.studentmanager.constant.Constant;
import com.habdqn.studentmanager.constant.DictType;
import com.habdqn.studentmanager.constant.ErrorCode;
import com.habdqn.studentmanager.exception.StudentException;
import com.habdqn.studentmanager.service.ClassesService;
import com.habdqn.studentmanager.service.DictionaryService;
import com.habdqn.studentmanager.service.EmploymentService;
import com.habdqn.studentmanager.service.ProductService;
import com.habdqn.studentmanager.service.StudentService;
import com.habdqn.studentmanager.util.DateUtil;

/**
 * 就业信息控制层
 * 
 * @author Administrator
 * 
 *         2017年5月22日
 *
 */
@Controller
@RequestMapping("/employment")
public class EmploymentController extends BaseController {
	private static Logger logger = Logger.getLogger(EmploymentController.class);

	@Resource
	private EmploymentService employmentService;

	@Resource
	private DictionaryService dictionaryService;

	@Resource
	private StudentService studentService;

	@Resource
	private ClassesService classesService;

	@Resource
	private ProductService productService;

	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String toAdd(Model model) {
		List<Dictionary> employmentTypes = dictionaryService
		        .findList(Dictionary.make(DictType.EmploymentType, null, null));
		List<Dictionary> companyTypes = dictionaryService.findList(Dictionary.make(DictType.CompanyType, null, null));
		List<Dictionary> companyScales = dictionaryService.findList(Dictionary.make(DictType.CompanyScale, null, null));
		List<Classes> classes = classesService.findList(null, 1, 0).getList();
		List<Product> products = productService.findProductList(1, 0, null).getList();
		model.addAttribute("classes", classes);
		model.addAttribute("products", products);
		model.addAttribute("employmentTypes", employmentTypes);
		model.addAttribute("companyTypes", companyTypes);
		model.addAttribute("companyScales", companyScales);
		return "employment/add";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String add(@ModelAttribute Employment bean, Model model) {
		try {
			Verify.verifyNull(bean);
			Verify.verifyEmpty(bean.getStudent().getId());
			Verify.verifyNull(bean.getTeacher().getId());
			Verify.verifyEmpty(bean.getCompanyName());
			Verify.verifyEmpty(bean.getJob());
			// Verify.verifyNull(bean.getCompanyType());
			// Verify.verifyNull(bean.getCompanyType().getValue());
			Verify.verifyEmpty(bean.getEmploymentCity());
			// Verify.verifyNull(bean.getCompanyScale());
			// Verify.verifyNull(bean.getCompanyScale().getValue());
			Verify.verifyEmpty(bean.getIsCorrespond());
			Verify.verifyNull(bean.getSalary());
			// Verify.verifyEmpty(bean.getExt3());
			employmentService.add(bean);
		}
		catch (VerifyException e) {
			logger.error("参数错误", e);
			model.addAttribute("msg", e.getMessage());
			return "error";
		}
		catch (StudentException e) {
			logger.error(e.getMessage(), e);
			model.addAttribute("msg", e.getMessage());
			return "error";
		}

		return "redirect:/employment/list";
	}

	/**
	 * 获得就业列表
	 * 
	 * @return
	 */
	@RequestMapping("/list")
	public String getEmploymentList(@ModelAttribute("student") Student bean,
	        @ModelAttribute("salary") BigDecimalCondition salary,
	        @ModelAttribute("employmentDate") DateCondition employmentDate,
	        @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
	        @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize, Model model) {
		try {
			List<Dictionary> products = dictionaryService.findList(Dictionary.make(DictType.ProductType, null, null));
			List<Dictionary> educations = dictionaryService
			        .findList(Dictionary.make(DictType.EducationType, null, null));
			PageInfo<Employment> page = employmentService.findList(bean, salary, employmentDate, pageNum, pageSize);
			model.addAttribute("pageInfo", page);
			model.addAttribute("products", products);
			model.addAttribute("educations", educations);
			List<Classes> classes = classesService.findList(null, 1, 0).getList();
			addAttr(model, "classes", classes);
		}
		catch (StudentException e) {
			logger.error("查询就业列表失败", e);
			model.addAttribute("msg", e.getMessage());
			return "error";
		}
		return "employment/list";
	}

	@RequestMapping("/toUpdate")
	public String toUpdate(Employment bean, Model model) {
		try {
			Verify.verifyNull(bean);
			Verify.verifyEmpty(bean.getId().toString());
			List<Dictionary> employmentTypes = dictionaryService
			        .findList(Dictionary.make(DictType.EmploymentType, null, null));
			List<Dictionary> companyTypes = dictionaryService
			        .findList(Dictionary.make(DictType.CompanyType, null, null));
			List<Dictionary> companyScales = dictionaryService
			        .findList(Dictionary.make(DictType.CompanyScale, null, null));
			List<Classes> classes = classesService.findList(null, 1, 0).getList();
			List<Product> products = productService.findProductList(1, 0, null).getList();
			model.addAttribute("classes", classes);
			model.addAttribute("products", products);
			model.addAttribute("employmentTypes", employmentTypes);
			model.addAttribute("companyTypes", companyTypes);
			model.addAttribute("companyScales", companyScales);
			bean = employmentService.find(bean);
			model.addAttribute("bean", bean);

		}
		catch (VerifyException e) {
			logger.error("参数错误", e);
			model.addAttribute("msg", "参数错误");
			return "error";
		}
		catch (StudentException e) {
			logger.error("获取就业信息失败", e);
			model.addAttribute("msg", "获取就业信息失败");
			return "error";
		}
		return "employment/edit";
	}

	@RequestMapping("/update")
	public String update(Employment bean,Model model) {
		try {
			Verify.verifyNull(bean);
			Verify.verifyNull(bean.getId());
			Verify.verifyEmpty(bean.getStudent().getId());
			Verify.verifyNull(bean.getTeacher().getId());
			Verify.verifyEmpty(bean.getCompanyName());
			Verify.verifyEmpty(bean.getJob());
			Verify.verifyEmpty(bean.getEmploymentCity());
			Verify.verifyEmpty(bean.getIsCorrespond());
			Verify.verifyNull(bean.getSalary());
			employmentService.update(bean);
		}
		catch (VerifyException e) {
			logger.error("非法参数", e);
			model.addAttribute("msg", "非法参数");
			return "error";
		}
		catch (StudentException e) {
			logger.error("系统错误", e);
			model.addAttribute("msg", "系统错误");
			return "error";
		}
		addAttr(model, "msg", "修改成功");
		return "success";
	}

	@RequestMapping(value = "/info")
	public String info(Employment bean, Model model) {
		try {
			Verify.verifyNull(bean);
			Verify.verifyEmpty(bean.getId().toString());
			bean = employmentService.find(bean);
			model.addAttribute("bean", bean);

		}
		catch (VerifyException e) {
			logger.error("参数错误", e);
			model.addAttribute("msg", "参数错误");
			return "error";
		}
		catch (StudentException e) {
			logger.error("获取就业信息失败", e);
			model.addAttribute("msg", "获取就业信息失败");
			return "error";
		}
		return "employment/info";
	}

	@RequestMapping(value = "/delete")
	@ResponseBody
	public Response del(Integer id) {
		Response res = new Response();
		try {
			Verify.verifyNull(id);
			int i = employmentService.realDel(id);
			if (i != 1) {
				res = Response.make(ErrorCode.Notfound, "没有找到指定信息");
			}
		}
		catch (VerifyException e) {
			logger.error("非法参数", e);
			res = Response.make(ErrorCode.Invalid_Argument, e.getMessage());
		}
		catch (StudentException e) {
			logger.error("系统错误", e);
			res = Response.make(ErrorCode.System_Error, e.getMessage());
		}
		return res;
	}

	/**
	 * 导出就业信息
	 * 
	 * @return
	 */
	@RequestMapping(value = "export")
	public String export(Student bean, BigDecimalCondition salary, DateCondition employmentDate,
	        HttpServletResponse response, Model model) {
		String fileName = DateUtil.format(DateUtil.now(DateUtil.CHINA_TIMEZONE), DateUtil.FormatStr14) + ".xlsx";
		try {
			OutputStream out = response.getOutputStream();
			// 设置强制下载不打开
			response.setContentType("applicaton/force-download");
			// 设置文件名
			response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
			employmentService.export(bean, salary, employmentDate, out);
		}
		catch (IOException e) {
			logger.error("请求异常", e);
			model.addAttribute(Constant.ERROR_MSG, "请求异常");
			return Constant.ERROR_PAGE;
		}
		catch (StudentException e) {
			model.addAttribute(Constant.ERROR_MSG, e.getMessage());
			return Constant.ERROR_PAGE;
		}

		return null;
	}

	/**
	 * 转发至导入页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/import")
	public String toImport() {

		return "employment/import";
	}

	@RequestMapping(value = "/import", method = RequestMethod.POST)
	public String importEmp(@RequestParam("file") CommonsMultipartFile file, Model model) {
		try {
			InputStream is = file.getInputStream();
			employmentService.importEmp(is);
		}
		catch (StudentException e) {
			model.addAttribute(Constant.ERROR_MSG, e.getMessage());
			return "employment/import";
		}
		catch (RuntimeException e) {
			logger.error("系统异常", e);
			model.addAttribute(Constant.ERROR_MSG, "系统异常");
			return "employment/import";
		}
		catch (IOException e) {
			logger.error("打开上传文件失败", e);
			model.addAttribute(Constant.ERROR_MSG, "打开上传文件失败");
			return "employment/import";
		}
		model.addAttribute("success", "导入成功");
		return "employment/import";
	}
}
